from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
from backend.app import db
def get_lottery_model():
    from backend.models.lottery_result import LotteryResult
    return LotteryResult
from backend.services.lottery_service import LotteryService
from datetime import datetime
import re

lottery_bp = Blueprint('lottery', __name__)
lottery_service = LotteryService()

@lottery_bp.route('/update', methods=['POST'])
@jwt_required()
def update_lottery_data():
    """更新双色球数据"""
    try:
        result = lottery_service.update_lottery_data()
        return jsonify({
            'message': '数据更新成功',
            'new_count': result.get('new_count', 0),
            'total_count': result.get('total_count', 0)
        }), 200
    except Exception as e:
        return jsonify({'error': f'数据更新失败: {str(e)}'}), 500

@lottery_bp.route('/list', methods=['GET'])
@jwt_required()
def get_lottery_list():
    """获取双色球数据列表"""
    try:
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        start_date = request.args.get('start_date')
        end_date = request.args.get('end_date')
        draw_number = request.args.get('draw_number')  # 添加期数查询参数
        red_ball_1 = request.args.get('red_ball_1', type=int)
        red_ball_2 = request.args.get('red_ball_2', type=int)
        red_ball_3 = request.args.get('red_ball_3', type=int)
        red_ball_4 = request.args.get('red_ball_4', type=int)
        red_ball_5 = request.args.get('red_ball_5', type=int)
        red_ball_6 = request.args.get('red_ball_6', type=int)
        
        LotteryResult = get_lottery_model()
        # 构建查询
        query = LotteryResult.query
        
        # 日期筛选
        if start_date:
            try:
                start_date_obj = datetime.strptime(start_date, '%Y-%m-%d').date()
                query = query.filter(LotteryResult.draw_date >= start_date_obj)
            except ValueError:
                pass
        
        if end_date:
            try:
                end_date_obj = datetime.strptime(end_date, '%Y-%m-%d').date()
                query = query.filter(LotteryResult.draw_date <= end_date_obj)
            except ValueError:
                pass
        
        # 期数筛选
        if draw_number:
            query = query.filter(LotteryResult.draw_number == draw_number)
        
        # 红球筛选
        if red_ball_1:
            query = query.filter(LotteryResult.red_ball_1 == red_ball_1)
        if red_ball_2:
            query = query.filter(LotteryResult.red_ball_2 == red_ball_2)
        if red_ball_3:
            query = query.filter(LotteryResult.red_ball_3 == red_ball_3)
        if red_ball_4:
            query = query.filter(LotteryResult.red_ball_4 == red_ball_4)
        if red_ball_5:
            query = query.filter(LotteryResult.red_ball_5 == red_ball_5)
        if red_ball_6:
            query = query.filter(LotteryResult.red_ball_6 == red_ball_6)
        
        # 排序和分页
        query = query.order_by(LotteryResult.draw_date.desc())
        pagination = query.paginate(
            page=page, 
            per_page=per_page, 
            error_out=False
        )
        
        # 格式化结果
        results = [item.to_dict() for item in pagination.items]
        
        return jsonify({
            'data': results,
            'pagination': {
                'page': page,
                'per_page': per_page,
                'total': pagination.total,
                'pages': pagination.pages,
                'has_next': pagination.has_next,
                'has_prev': pagination.has_prev
            }
        }), 200
        
    except Exception as e:
        return jsonify({'error': f'获取数据失败: {str(e)}'}), 500

@lottery_bp.route('/statistics', methods=['GET'])
@jwt_required()
def get_statistics():
    """获取统计数据"""
    try:
        LotteryResult = get_lottery_model()
        total_count = LotteryResult.query.count()
        latest_draw = LotteryResult.query.order_by(LotteryResult.draw_date.desc()).first()
        
        return jsonify({
            'total_count': total_count,
            'latest_draw': latest_draw.to_dict() if latest_draw else None
        }), 200
        
    except Exception as e:
        return jsonify({'error': f'获取统计数据失败: {str(e)}'}), 500

@lottery_bp.route('/range', methods=['GET'])
@jwt_required()
def get_draw_range():
    """获取期数范围"""
    try:
        LotteryResult = get_lottery_model()
        # 获取最新的期数
        latest = LotteryResult.query.order_by(LotteryResult.draw_date.desc()).first()
        # 获取最早的期数
        earliest = LotteryResult.query.order_by(LotteryResult.draw_date.asc()).first()
        
        return jsonify({
            'latest_draw': latest.draw_number if latest else None,
            'earliest_draw': earliest.draw_number if earliest else None,
            'total_count': LotteryResult.query.count()
        }), 200
        
    except Exception as e:
        return jsonify({'error': f'获取期数范围失败: {str(e)}'}), 500 